package com.cyzy.util;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.KeyGenerator;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Date;

@Component
public class JwtUtil {

    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;
    public String generateToken(String userId) {
        System.out.println("生成Token for用户ID: " + userId);
        System.out.println("使用的密钥: " + secret);
        System.out.println("过期时间(毫秒): " + expiration);
        
        String token = Jwts.builder()
                .setSubject(userId)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
                
        System.out.println("生成的Token: " + token);
        return token;
    }

    public Integer getUserIdFromToken(String token) {
        String userId = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
        return Integer.parseInt(userId);
    }

    public boolean validateToken(String token) {
        try {
            System.out.println("开始验证Token: " + token);
            System.out.println("使用的密钥: " + secret);
            
            Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
            System.out.println("Token验证成功");
            return true;
        } catch (Exception e) {
            System.out.println("Token验证失败，异常类型: " + e.getClass().getSimpleName());
            System.out.println("Token验证失败，异常信息: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 检查Token是否即将过期（还有不到1小时）
     */
    public boolean isTokenExpiringSoon(String token) {
        try {
            Date expirationDate = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody()
                    .getExpiration();
            
            // 检查是否在1小时内过期
            long timeUntilExpiration = expirationDate.getTime() - System.currentTimeMillis();
            return timeUntilExpiration < 3600000; // 1小时 = 3600000毫秒
        } catch (Exception e) {
            return true; // 解析失败说明Token有问题，认为即将过期
        }
    }
    
    /**
     * 获取Token剩余有效时间（秒）
     */
    public long getTokenRemainingTime(String token) {
        try {
            Date expirationDate = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody()
                    .getExpiration();
            
            long remainingTime = expirationDate.getTime() - System.currentTimeMillis();
            return Math.max(0, remainingTime / 1000); // 转换为秒
        } catch (Exception e) {
            return 0;
        }
    }

    public static String generateSecret() throws NoSuchAlgorithmException {
        KeyGenerator ketGenerator= KeyGenerator.getInstance("HmacSHA256");
        ketGenerator.init(256);

        return Base64.getEncoder().encodeToString(ketGenerator.generateKey().getEncoded());
    }
}
